简体   繁体   中英

How can I avoid using the async keyword everywhere?

Using Javascript, consider the following situation:

  • Somewhere Deep in the call stack
  • Something becomes a Promise

This can happen for any number of reasons.

// a calls b, calls c, and so on.

function z(){
    // Let's say this:
    // return 4;
    // Became this:
    return new Promise( (resolve, reject) => resolve(4) );
}

Function Y can no longer use the 4 , as it's tied up in a promise. Fortunately, Function Y can await the promise, and then continue business as usual.

However, In order to use await , Function Y must use the async keyword, which forces Y to return a promise.

Now, Function X must become async to await Y , and Function W must become async to await X . On and on it goes, all the way back up the call tree.

In essence, a small change that introduces a promise can require a major refactor.

Is there a way to avoid this?

There is no way to safely turn an asynchronous method into a synchronous one. This is true for any programming language, not just JavaScript.

You could transform a Promise into:

  1. callbacks
  2. an event emitter
  3. a stream

You can use .then() instead of await , but you will still have the same problem that asynchrony propagates up the stack to the main() method unless you do one of the above options.

Once you start using asynchrony, it necessarily "poisons" any of the callers unless you throw away the result. Avoiding the use of the async/await keywords isn't getting rid of the asynchrony, it's just represented in code in a different form.

Don't recommend you this path, but try something like below maybe:

function Y(retVal) {
    if (retVal instanceof Promise){
        return (async function(){
            var result = await retVal;
            return  Y(result);
        }());
    } else {
        return retVal * 2;
    }
}

Y(4) //8;
Y(Promise.resolve(4))  //{<resolved>: 8}

有很多处理promise的方法,比如你可以使用async-await,.then(),所以如果任何新promise进入深层调用堆栈并且你没有任何使用async-await的选项,那么使用Promises.then( ) 方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM