【问题标题】:How do I write async/await code without chaining and nesting a bunch of promises?如何在不链接和嵌套一堆 Promise 的情况下编写 async/await 代码?
【发布时间】:2018-10-16 02:33:16
【问题描述】:

我在这个问题上有点挣扎。

比如说,我需要一个值才能做其他工作。

要检索值,我需要进行 API 调用。

在我正常的编程大脑中,我想这样做:

let x = api.getLocationOfUser('user154');

后跟其他代码如:

let y = geo.getTaxRulesByLocationId(x.location_id);

是通过嵌套实现这一点的唯一方法吗?

【问题讨论】:

  • 正如你的标题所说,使用await..? let x = await api...(确保它返回一个消耗品Promise)如果这不起作用,您可以发布您当前的代码(或示例代码)嵌套过多,以便我们可以看到您在处理什么?跨度>

标签: javascript node.js ecmascript-6


【解决方案1】:

也许您正面临一个名为 CallbackHell 的问题。

function myfunc() {
    otherFunctionThatReturnsPromise.then((a) => {
        otherFunction(a).then((b) => {
            // Do stuff
            console.log(b);
        });
    });
}

试试下面的代码:

async function myfunc() {

   let a = await otherFunctionThatReturnsPromise();

   // This line wont be executed until the upper line returns with a resolved Promise
   let b = await otherFunction(a);
}

参考the MDN site

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2018-02-05
    • 2019-09-14
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多