最简用  promise

let res = function () {
return new Promise((resolve, reject) => { // 返回一个promise
setTimeout(() => {
resolve(10)
}, 3000)
})
}
res().then(x => { // promise.then()
let a = 20;
a += x
console.log(a);
})

多个异步用 async

let res = function () {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(10)
},3000)
})
}
async function test(){
console.log('before'); // 按顺序输出 before b after
let b=await res() // 可以按顺序执行多个 promise
b+=30;
console.log('b',b);
console.log('after');
} test();

async 返回 promise (直接在async函数里面操作就行了,不要再返回了)

let res = function () {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(10)
},3000)
})
}
async function test(){
let b=await res()
console.log('b',b);
b+=30;
return b; // async 返回一个 promise
} let cc=0
test().then(x=>{ // promise then
cc=x;
console.log('cc',cc);
})

async  try.. catch..

let res = function (val) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (val > 3) { resolve(10)
} else {
reject(false)
}
}, 3000)
})
} async function test (val) {
try {
let b = await res(val)
b+=20;
console.log('b',b);
} catch (e) { // promise有 reject时 要 try()catch{}
if (e) {
console.log('b is true');
}else{
console.log('b is false');
}
}
} test(10);

promise try-catch

let res = function (val) {
return new Promise((resolve, reject) => { // 返回一个promise
setTimeout(() => {
if (val > 10) {
resolve(10)
}else{
reject('no4')
}
}, 3000)
})
}
res(1).then(x => { // promise.then()
let a = 20;
a += x
console.log(a);
}).catch(e=>{
if(e==='no'){
console.log('hahaha');
}else{
console.log('no input');
}
})

传统回调函数

let f = function (test) { // 传入一个函数
setTimeout(()=>{
let a = 10
test(a) // 把结果给一个函数
},3000)
}
f(function (val) {
console.log(val); //
})

promise 链式调用    promise.then().then()

/*
* promise.then(res=>{
* return p2 // promise的then 可以return 一个 Promise 即执行下一个promise,其结果可以继续then()获取
* }).then(res2=>{})
*
* */
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
}) let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2)
}, 2000)
})
let p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3)
}, 3000)
})
p1.then((res) => {
console.log(res) // 第一个值
return p2 // then中返回下一个promise 可再加个 then 接收第二个值
}).then(res2 => {
console.log(res2)
return p3
}).then(res3 => {
console.log(res3)
console.log('end')
})

promise  nodejs readFile

var fs = require('fs')

function readFile (filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
} readFile('./a.txt')
.then(data => {
console.log(data)
return readFile('./b.txt')
}).then(data2 => {
console.log(data2)
return readFile('./c.txt')
}).then(data3 => {
console.log(data3)
})

jq 支持 链式调用  $.get().then().then()

// jq 支持 链式调用  $.get().then().then()
var data = {}
$.get('xxx').then(user => {
data.user = user
return $.get('yyy')
}).then(jobs => {
data.jobs = jobs
console.log(data) // {user:{},jobs:[]}
})

封装  ajax 为 promise 和 callback

// 封装  ajax 为 promise 和 callback
/*
* XMLHttpRequest.DONE === 4 mdn
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText)
}
* xhr.onload = function () {
console.log('DONE', xhr.readyState); // readyState 为 4
};
* */
function apiGet (url, callback) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.onload = function () { // 不是标准。
callback && callback(JSON.parse(xhr.responseText)) // 回调
resolve(JSON.parse(xhr.responseText))
}
xhr.onerror = function (err) {
reject(err)
}
xhr.open('get', url, true)
xhr.send()
})
} // json-server -w a.json -p 1234
apiGet('http://localhost:1234/posts').then(res => {
console.log(res)
})
/*
apiGet('http://localhost:1234/posts',function (res) {
console.log(res)
})*/

promise async的更多相关文章

  1. vue使用技巧:Promise + async + await 解决组件间串行编程问题

    业务场景描述 大家都通过互联网投递过简历,比如在智联.58.猎聘等平台.投递心仪的职位前一般都需要前提创建一份简历,简历编辑界面常规的布局最上面是用户的个人基本信息,如姓名.性别.年龄.名族等,接着是 ...

  2. nodejs 回调地狱解决 promise async

    nodejs毁掉地狱是一直被人诟病的,以下总结一下解决毁掉地狱的一些方法.(暂时研究的比较浅) 1.promise promise模式在任何时刻都处于以下三种状态之一:未完成(unfulfilled) ...

  3. angular2 学习笔记 ( Rxjs, Promise, Async/Await 的区别 )

    Promise 是 ES 6 Async/Await 是 ES 7 Rxjs 是一个 js 库 在使用 angular 时,你会经常看见这 3 个东西. 它们都和异步编程有关,有些情况下你会觉得用它们 ...

  4. promise async await使用

    1.Promise (名字含义:promise为承诺,表示其他手段无法改变) Promise 对象代表一个异步操作,其不受外界影响,有三种状态: Pending(进行中.未完成的) Resolved( ...

  5. Promise,async/await解决回调地狱

    先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行. 写一个async 函数 as ...

  6. ES6 class setTimeout promise async/await 测试Demo

    class Person { async getVersion () { return new Promise((resolve, reject) => { setTimeout(functio ...

  7. lazy evaluation and deferring a computation await promise async

    Promise - JavaScript | MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_ ...

  8. promise, async和await

    最开始实现异步的方法:回调函数 method1(function(err, result) { if (err) { throw err; } method2(function(err, result ...

  9. 一眼看懂promise async的区别

    // promise方法 let p1 = new Promise((resolve,reject) => { setTimeout(() => { resolve('我是p1') },4 ...

随机推荐

  1. pymysql模块

    一.pymysql模块 1.说明: 想在python代码中连接上mysql数据库,就需要使用pymysql模块, pymysql是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,在 ...

  2. 读取Excel2003、Excel2007或更高级的兼容性问题 workbook 下载中文名称文件

    xls 使用HSSFWorkbook xlsx使用XSSFWorkbook 但是我使用XSSFWorkbook时没找到nuget包,引用不了,只能重新找办法,幸好workbook解决了我这个问题 // ...

  3. [SCOI2009] 迷路

    题目类型:拆点, 矩阵快速幂 转化为矩阵快速幂,好题! 传送门:>Here< 题意:给出邻接矩阵,求\(1\)到\(N\)恰好长度为\(T\)的路径方案数 解题思路 如果题目给出的是一个\ ...

  4. mongoDB 文档操作_查

    基本查询命令 find 查找复合条件的所有文档 命令 db.collection.find(query,field) 参数 query 查找条件 格式: {ssss:"xxx"}是 ...

  5. L2-006 树的遍历 (25 分) (根据后序遍历与中序遍历建二叉树)

    题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456 L2-006 树的遍历 (25 分 ...

  6. mysql shell 定时备份

    #!/bin/sh if [ ! -d "/data/backup" ]; then         mkdir -p /data/backup fi db_user=" ...

  7. Gym - 101350E Competitive Seagulls (博弈)

    There are two seagulls playing a very peculiar game. First they line up N unit squares in a line, al ...

  8. python list的使用

    list列表的常用方法有: #!/usr/bin/env python # -*- coding:utf- -*- #以下方法全在python2..x版本运行,请3.x以上的小伙伴们在print(放入 ...

  9. androidstudio上传代码到git上

    1.首先通过git --bare init 在服务端创建好了一个git仓库:假设git仓库在服务端的地址为:/user/lyh/project/test.git 2.androidstudio上点击V ...

  10. 在CentOS 上搭建nginx来部署静态页面网站

    在centOs 上搭建nginx来部署静态页面网站 一.部署服务器环境 nginx:轻量级.高性能的HTTP及反向代理服务器,占用内存少,并发能力强,相比老牌的apache作为web服务器,性能更加卓 ...