节点异步/等待递归函数结束代码执行

我对节点异步等待和递归函数有问题。由于某种原因,在解决了递归函数的Promise之后,代码执行将停止。下面只是我用来演示我的问题的一个简单示例(尽管在通过请求库发送一些请求时发现了问题)。

如果运行代码,您将看到

async

,但不是“测试已完成”。

Starting
Inside Promise

有人可以请教出什么问题吗?

谢谢。

ilys2013 回答:节点异步/等待递归函数结束代码执行

以下是一些修复方法:

function promiseFunc(number) {
    return new Promise((resolve,reject) => {
        if (number == 100) {
            console.log('Inside Promise');
            resolve('Done');
        } else {
            number += 1;
            resolve(promiseFunc(number));
        }
    })
}


(async function testFunc() {
    console.log('Starting');
    await promiseFunc(0)
    console.log("Test completed");
})()

或者,有趣的是,使用async / await而不是显式new Promise(...)的等效代码适用于您的情况:

// an async function returns a Promise
async function promiseFunc(number) {
        if (number == 100) {
            console.log('Inside Promise');
            return 'Done';
        } else {
            number += 1;
            // it seems to work as intended without saying return promiseFunc(...)
            promiseFunc(number);
        }
    }


(async function testFunc() {
    console.log('Starting');
    await promiseFunc(0)
    console.log("Test completed");
})()
,

你必须这样做

  function promiseFunc(number) {
    return new Promise((resolve,reject) => {
        http.post('/api')
        .then((data) => {
            resolve(data);
        })
    })
}

    (async function testFunc() {
    console.log('Starting');
    const result = [];
    for (let index = 0; index < 100; index++) {
        result[index] = await promiseFunc(0);
    }
    console.log("Test completed");
})()
本文链接:https://www.f2er.com/3152732.html

大家都在问