我一直在將一個值綁定到下一個Promise時遇到問題。看下面的代碼,它會更好地解釋情況。Promise.then綁定問題
'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'
});
問題是,爲什麼它綁定的值在兩種情況下都不相同。兩者是完全一樣的,除了這一個是首先解決承諾的一部分,然後分配一個值爲payload.userId
。
在MyServiceWorks你正在返回的承諾,但在findUser要返回Promise.resolve – Avinash
那麼它與在未來的承諾結合的值呢? –
我想你可能想嘗試'返回新的Promise.resolve(有效載荷);'在'MyServiceProblem'中。 '新'很重要。 – Ali