无法将价值传递到承诺链

Can't pass value down promise chain

在我的代码中我有...

p.then(() => { console.log('Then 1'); return 'Hi Mum!!'});

...和

p.then(function(val) { console.log('Then 2: ' + val);

解决承诺时的输出...

Then 1 Then 2: undefined

如何从 Then 2 中的 Then 1 访问 return?

这不是 ,您在初始承诺上注册第二个延续,而不是从前一个 then 调用返回的承诺。它应该是这样的:

p.then(() => { console.log('Then 1'); return 'Hi Mum!!'})
 .then(function(val) { console.log('Then 2: ' + val) });

另一种方法是将第一个 分配给一个变量并提供 then 调用:

const chain = p.then(() => { console.log('Then 1'); return 'Hi Mum!!'})
// ...
chain.then(function(val) { console.log('Then 2: ' + val); });

这允许您传递承诺链并且仍然传递预期值。