promise用法 发表于 2019-05-09 | 更新于 2019-05-10 | 分类于 学习笔记原本层层嵌套改为多个then和catch连写的方式123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263var request = require('request');var url = "'http://httpbin.org/get'";function test(url) { // 语法检查 "use strict"; return new Promise(function(resolve,reject){ request( url, function(err, response, body){ if(!err && response.statusCode == 200) { resolve(body); }else { reject(err); } } ); });}test('http://httpbin.org/get') .then(function(value){ return value; }) .then(function(value){ // console.log(22222); // console.log(value); }) .catch(function(value){ });//语法糖方式var prom = Promise.resolve( //返回的是promise对象,这里远程get方式无法调用 request(url,function(err, response, body){}));prom.then(function(value){ // console.log(value.uri);});// 只要抛错误就直接调用catchfunction task1() { console.log('task1'); throw new Error('error test');}function task2() { console.log('task2');}function err() { console.log('err');}var prom = Promise.resolve('aaaaa');// prom.then(task1).then(task2).catch(err);