【问题标题】:executing code inside setTimeout in a asynchronous function?在异步函数中执行 setTimeout 内的代码?
【发布时间】:2022-01-21 01:03:00
【问题描述】:

一个简单的脚本,我想要实现的是在 append 方法中推送新项目,并使用异步函数

我试图了解 then 和 catch 是如何工作的,而不是在不了解它们内部如何工作的情况下使用它们(使用 axios 或其他东西)

必须在 3 秒后执行推送

我尝试在setTimeout 中使用resolve 方法,但出现错误,因为resolve 无法识别,我正在返回一个Promise,因为我无法等待setTimeout

<script>

    async function test(terms) {
        let termss = await append(terms);
        return [termss[termss.length - 2], termss[termss.length - 1]]
    }

    async function append(arr) {
        var arrr = arr;

        const waitFor = () => new Promise(resolve => {
            setTimeout((resolve) => {
                arrr.push("Taoufiq")
                arrr.push("understands");
            }, 3000)
        });

        await waitFor();

        return arrr;
    }

    test([1, 2, 3, 9]).then((result) => {
        console.log(result)
    })

</script>

Ayy 帮助了解它是如何工作的?

我的预期结果是返回一个带有 ["Taoufiq", "understands"] 的数组

【问题讨论】:

  • 您确实需要兑现承诺。看看at this example 看看它的实际效果。无需将resolve 传递给超时函数。它在范围内。

标签: javascript asynchronous settimeout es6-promise


【解决方案1】:

你应该可以用下面的代码做你想做的事:

async function test(terms) {
    let termss = await append(terms);
    return [termss[termss.length - 2], termss[termss.length - 1]]
}

async function append(arr) {
    return new Promise(resolve => {
        setTimeout(() => {
            arr.push("Taoufiq")
            arr.push("understands");
            resolve(arr)
        }, 3000)
    });
}

test([1, 2, 3, 9]).then((result) => {
    console.log(result)
})

因此,您必须在 append 函数中返回新的 Promise,并使用 Promise 构造函数在 setTimemout 中提供给您的 resolve 方法。

【讨论】:

  • 感谢您写这篇文章,这是正确的,但您也写了一些帮助我理解的东西,所以 resolve(param) 或 reject(param) 是返回值的方法,所以等待 Promise 返回值在 res 或 rej 方法中,不是吗?就像退货的替代品
  • @TaouBen 是的,你是对的。您可以使用 resolve 和 reject 方法从 Promise 内部返回一个值,并且您可以使用 then、catch 或 await“等待”该 Promise 之外的值。请注意,如果您执行const res = await promise() 之类的操作,如果promise 抛出错误,您必须将该语句包装在try..catch 块中以获取错误。您可以在文档中找到所有内容的任何方式。
猜你喜欢
  • 1970-01-01
  • 2017-09-25
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多