栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么我的诺言返回未定义?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么我的诺言返回未定义?

因为

throttleAsync
返回调用的结果
promise.then
,并且
then
回调不返回任何内容。这使得通过
then
解决创造的承诺具有价值
undefined

您可能打算让它返回您正在创建的新的Promise,但是直到

setTimeout
回调之前您都不会这样做。您想事先做(但还有更多,请继续阅读):

let throttleAsync = function(url) {    return promise.then(() => {        return new Promise( fulfil => { setTimeout(anUrl => {     fulfil(asyncMock(anUrl)); }, throttleMs, url);        });    });};

也没有理由

setTimeout
像这样传递URL ,因此:

let throttleAsync = function(url) {    return promise.then(() => {        return new Promise( fulfil => { setTimeout(() => {     fulfil(asyncMock(url)); }, throttleMs);        });    });};

最初,我虽然

promise
没有必要,但是您已经澄清了,您想确保重复的呼叫由隔开
throttleMs
。为此,我们将使用上面的方法,但要进行更新
promise

let throttleAsync = function(url) {    return promise = promise.then(() => {    //     ^^^^^^^^^        return new Promise( fulfil => { setTimeout(() => {     fulfil(asyncMock(url)); }, throttleMs);        });    });};

这样,下一个呼叫

asyncThrottle
将一直等到前一个触发后再开始下一个。

现场示例:

const throttleMs = 1000;const asyncMock = url => url;let promise = Promise.resolve();let throttleAsync = function(url) {    return promise = promise.then(() => {    //     ^^^^^^^^^        return new Promise( fulfil => { setTimeout(() => {     fulfil(asyncMock(url)); }, throttleMs);        });    });};console.log('running');throttleAsync('http://www.bananas.pt')    .then(console.log)    .catch(console.error);throttleAsync('http://www.fruits.es')    .then(console.log)    .catch(console.error);throttleAsync('http://www.veggies.com')    .then(console.log)    .catch(console.error);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号