如何正确地称这个承诺链

sho*_*a T 2 javascript promise

我使用以下代码与blueBird lib,但在控制台我得到错误:

未捕获的TypeError:无法读取未定义的属性'then'

我在那时([SUCESS])没有看到console.log 为什么?

我有两个文件1.index.html,代码如下

<html>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.1.1/bluebird.js'></script>
Run Code Online (Sandbox Code Playgroud)
  1. 和script.js使用以下代码

var stepOne = new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log("Step 1 -->Successfully Resolving");
        resolve();
    }, 5000);
    setTimeout(function () {
        console.log("Step 1 -->First timeout, rejecting the promise");
        reject();
    }, 2000);
}).catch(function () {
        console.log("Step 1 -->Timed out 1 ... retrying");
    });


var stepTwo = new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log("Step 2 -->Successfully Resolving Step two");
        resolve();
    }, 5000);
    setTimeout(function () {
        console.log("Step 2 -->First timeout, rejecting the promise");
        reject();
    }, 2000);
}).catch(function () {
        console.log("Step 2 -->timed out 2 ... retrying");
    });


stepOne.then(function () {
    console.log("[SUCCESS] Step 1");
}).stepTwo.then(function () {
        console.log("[Success] Step 2");
    })
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 5

你对Promise是什么有一点误解.Promise是的代理,而不是操作的代理.传递给Promise构造函数的代码会立即执行,因此您的代码将始终一次运行,而不是一个接一个地运行.(你不能"运行"一个Promise,就像你不能"运行"一个数字或一个布尔值.但是,你可以运行一个函数)

你想要做的是有step1step2 功能,其返回一个承诺.

const step1 = () => new Promise(...); // Step 1 code in this promise
const step2 = () => new Promise(...); // Step 2 code in this promise

// By this point, nothing runs, we only defined functions.

step1() // Run step one
  .then(() => console.log('[SUCCESS] Step 1');
  .then(step2); // Run step two
  .then(() => console.log('[SUCCESS] Step 2');
Run Code Online (Sandbox Code Playgroud)