gpt4 book ai didi

javascript - Promise.then 绑定(bind)问题

转载 作者:行者123 更新时间:2023-11-28 18:47:00 24 4
gpt4 key购买 nike

我在将值绑定(bind)到下一个 Promise 时遇到了问题。看下面的代码,它会更好地解释情况。

'use strict';

function FindEvent(eventId) {
console.log('Event:', eventId);
return Promise.resolve({title: 'MyEvent'});
}

function FindUser(userId) {
console.log('User:', userId);
return Promise.resolve({username: 'MyUser'});
}

function MyServiceProblem(payload) {
payload.userId = 'blah';
return FindEvent(payload.eventId)
.then((event) => {
payload.userId = 'test';
// setting a breakpoint here shows
// that the value to payload.userId has been
// assigned, i.e. 'test'

return Promise.resolve(payload);
})
.then(FindUser.bind(this, payload.userId));
// But new value doesn't reaches inside FindUser
}

MyServiceProblem({ // userId is 'blah', why not 'test'
eventId: '456'
});

function MyServiceWorks(payload) {
payload.userId = 'blah';
return new Promise((resolve) => {
payload.userId = 'test';

return resolve(payload);
})
.then(FindUser.bind(this, payload.userId));
// From here, the 'test' value reaches FindUser
}

MyServiceWorks({ // userId is 'test'
eventId: '456'
});

问题是,为什么这两种情况它绑定(bind)的值不同。两者完全相同,只是这个首先解析 Promise 部分,然后为 payload.userId 赋值。

最佳答案

让我们稍微分解一下您的代码。你有

function MyServiceProblem(payload) {
payload.userId = 'blah';
return FindEvent(payload.eventId)
.then((event) => {
payload.userId = 'test';

return Promise.resolve(payload);
})
.then(FindUser.bind(this, payload.userId));
}

问题是您的 .bind 将在回调之前运行。这段代码也可以写成

function MyServiceProblem(payload) {
payload.userId = 'blah';

var firstThenCallback = (event) => {
payload.userId = 'test';
return Promise.resolve(payload);
};
var secondThenCallback = FindUser.bind(this, payload.userId);

return FindEvent(payload.eventId)
.then(firstThenCallback)
.then(secondThenCallback);
}

payload 对象在所有对象之间共享,但 payload.userIdfirstThenCallback 之前传递到 .bind > 有机会执行。

与其使用 .bind 并立即传递值,最简单的解决方案似乎是使用匿名函数,以便稍后读取 userId 值。

function MyServiceProblem(payload) {
payload.userId = 'blah';
return FindEvent(payload.eventId)
.then((event) => {
payload.userId = 'test';

return Promise.resolve(payload);
})
.then(() => FindUser(payload.userId));
}

也不清楚为什么你要编写如此迂回的 promise 代码,但我认为这是一个精简的示例?为什么要使用 payload 进行解析,而不是仅在该函数中调用 FindUser,例如

function MyServiceProblem(payload) {
payload.userId = 'blah';
return FindEvent(payload.eventId)
.then((event) => {
payload.userId = 'test';

return FindUser(payload.userId);
});
}

关于javascript - Promise.then 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35134191/

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