.then()这个方法什么意思?无意看到别人写的js代码有这个方法,度娘了一下,答案都很笼统

如题所述

    then()方法是异步执行。

    意思是:就是当.then()前的方法执行完后再执行then()内部的程序,这样就避免了,数据没获取到等的问题。

    语法:promise.then(onCompleted, onRejected);

    参数

    promise
    必需。
    Promise 对象。

    onCompleted
    必需。
    承诺成功完成时要运行的履行处理程序函数。

    onRejected
    可选。
    承诺被拒绝时要运行的错误处理程序函数。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-16
不太喜欢回答匿名的- - 因为往往他们都不做后续操作……
then()方法是异步执行
就是当.then()前的方法执行完后再执行then()内部的程序
这样就避免了,数据没获取到等的问题本回答被提问者采纳
第2个回答  2016-07-26

查一下ES6的 Promise A+规范吧, jQuery也在很早期就提供了deffered的API。


简单来说的话,thenable function是用来拍平callback hell的。

假设有以下代码,拿node举个例子

const fs = require('fs')
fs.readFile('path.txt', 'utf-8', (err, d1)=> {
     fs.readFile(d1, 'utf-8', (err,d2) => {
         fs.readFile(d2, 'utf-8', (err, d3) => {
              //以此类推,业务复杂起来,回调很容易超过10层,代码的维护性就直线下降了
         })
     })
})

而Promise能做什么呢

var read = function(file){
    return new Promise((resolve, reject) => {
        fs.readFile(file, 'utf-8', (err, d1) => {
            if(err) reject(err)
            else resolve(d1)
        })
    })
}

var chain = read('path.txt')
chain.then(d1 => read(d1))
         .then(d2 => read(d2))
         .then(d3 => read(d3))
         //...以此类推

第3个回答  2018-08-24
then()方法是异步执行
就是当.then()前的方法执行完后再执行then()内部的程序
第4个回答  2016-07-26
官方回答:

The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise.
语法如下:
p.then(onFulfilled, onRejected);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
相似回答