gpt4 book ai didi

javascript - 将其余代码作为回调函数传递

转载 作者:行者123 更新时间:2023-12-03 03:18:49 25 4
gpt4 key购买 nike

在已经完成的 JavaScript 函数中,您想要调用一个新的异步函数。因此,您需要将“其余代码”作为回调函数作为参数传递给这个新函数。

function sample() {
alert("a bunch of codes");

alert("another a bunch of codes");
}

我必须更改以下功能。

function sample() {
alert("a bunch of codes");

var cb = function () {
alert("another a bunch of codes");
};

newFunction(cb);
}

如果我想添加另一个必须等​​待第一个函数的函数怎么办?然后我得到了无数个多层回调函数来等待另一个..

那么 ES5 的最佳实践是什么?

最佳答案

在 ES5 中,就像你说的,你必须在彼此之间嵌套多个回调。

示例:

function myFunction2(){
console.log(2);

let myFunction = () => {
console.log(1);
}

myFunction();
}
myFunction2();
// OUTPUT
// 2
// 1

ES6还提供了一个新的替代方案,promises .

示例:

let myPromise = new Promise((resolve, reject) => {
setTimeout(function(){
resolve(1);
}, 250);
});

console.log(2);
myPromise.then((successMessage) => {
console.log(successMessage);
});
// OUTPUT
// 2
// 1

ES8 提供了一个更好的替代方案(尽管它只是基于 promise 的语法糖),但你可以使用 async带有await 的函数。

示例:

function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}


async function add1(x) {
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
}

add1(10).then(v => {
console.log(v); // prints 60 after 4 seconds.
});

但请记住,您可能需要使用 Babel 来转译您的 js 以便与所有浏览器兼容。

关于javascript - 将其余代码作为回调函数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46659839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com