'Does Google Apps Script V8 engine support Promise?

They say the V8 engine is a proper Javascript ES5 engine. Does it support ES5 features like Promise?



Solution 1:[1]

No. Promises are not functionally supported. But all promises related syntax is valid and doesn't throw any error. However everything runs synchronously.

async function promise1_() {
  Logger.log("Start")
  Utilities.sleep(10000);
  return "done";
}

function test1(){
  promise1_();
  Logger.log("End")
}

If promises worked, "End" should be logged before "Start", but that's not the case.

Solution 2:[2]

Apps script V8 recognizes the new function definition formats, for example:

let letAsyncFunction = async function() { //Your logic here }

It asynchronously returns the result of the function evaluations, pretty much like a Promise.

In other words, when the function async is called, it returns a promise. Also await is used for calling an async function and wait for it to resolve or reject


References:

Solution 3:[3]

Its a bit old yet still relevant.

My answer is No (Apr. 2022). Although syntactically and the way the code runs yes, but practically it is synchronous flow.

example:

function main() {
    console.log(Date(),"start");

    getStatAsync();
    
    console.log(Date(),"end");

}

 function getStatAsync(){

    let p = new Promise((res,rej)=>{
let url = "some url";
    
        let response = UrlFetchApp.fetch(url);

        let ans = parse(response);

        if (ans){
            res(ans);
        }else{
            rej("fetch faild");
        }
    })

  //resolved
    p.then((res) =>{
        console.log("fetch resolved",res);
    })

  //rejected
    p.catch((msg) => {
        console.log("fetch failure", msg );
    })

    function parse(response){
        let ans = null;

        let code = response.getResponseCode();

        if (code == "200" ) {
            ans = JSON.parse(response.getContentText());
          } else {
            console.error(` fetch failed code=${code}`);
          }

          return ans;
    }
}

main()

this is semi code fetching for a URL from within a Promise.

The promise is wrapping UrlFetchApp is within a promise that logs the fetch results either is the then or the catch callbacks.

The output for that would be:

  1. start
  2. end
  3. for successful fetch: fetch resolved

The end message is logged before the promise logging, indicating asynchronous execution. Without the promise end message become the last log line and the fetch resolved becomes last as in standard synchronous flow

However, assuming the fetch takes 10 sec, both end and fetch resolved are logged after those 10 sec.

The main code is suspended until fetch returned, although the log lines seems are printed like it is asynchronous flow

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 OJNSim