微信小程序,封装同步请求

封装统一请求的目的:在请求时有时会返回不同的返回码进行不同的数据处理,比如:返回正常时,进行正常操作,如果返回了异常,那么就需要进行不同的处理了,由于每次请求都可能出现各种返回码,所以进行请求封装,进行统一异常处理。

在小程序中提供的请求:

wx.request({

url: url,

data: params,

method: ‘POST‘,

header: {                ‘content-type‘: ‘application/x-www-form-urlencoded‘            },

success: function (result){

}})

默认是一个异步请求,我在封装时采用封装同步请求的方式。

在这里我使用了ES6中的 es6-promise,Promise的特点是同步操作,可以创建数个Promise对象,把需要同步的代码封装到Promise对象中

let promisevariable = new Promise(function (resolve, reject) {

wx.request({

url: servser+url,

data: params,

method: ‘POST‘,

header: {                ‘content-type‘: ‘application/x-www-form-urlencoded‘            },

success: function (result){

var status = result.statusCode;

if(status == 500){

//程序抛出异常

var exception = result.data.exception;

var msg = result.data.message;

var path = result.data.path;

wx.showToast({

title: exception+"\r\n"+msg+"\n\r"+path,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}

if(status != 200){

//系统未知异常

var msg = result.data.error;

var path = result.data.path;

wx.showToast({

title: msg+"\n\r"+path,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}                //自定义异常

var sta = result.data.status;

if(sta != 200){

var msg = result.data.message;

wx.showToast({

title: msg,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}

resolve(result);

//这里就是每个Promise对象的结果

}

});

});

然后把该对象按顺序放到一个数组中,使用Promise提供的方法 Promise.all

Promise.all([数组对象]).then(function(values) {

//这里就可以顺序执行并得到每个结果

console.log(values);

});

---------------------

//引入Promise

var Promise = require(‘./es6-promise.auto.js‘);

//获取服务器地址

var servser = getApp().data.servsers;

console.log(servser);

//默认请求

function sendRequest(url,params){

let promisevariable = new Promise(function (resolve, reject) {

wx.request({

url: servser+url,

data: params,

method: ‘POST‘,

header: {

‘content-type‘: ‘application/x-www-form-urlencoded‘

},

success: function (result){

var status = result.statusCode;

if(status == 500){

//程序抛出异常

var exception = result.data.exception;

var msg = result.data.message;

var path = result.data.path;

wx.showToast({

title: exception+"\r\n"+msg+"\n\r"+path,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}

if(status != 200){

//系统未知异常

var msg = result.data.error;

var path = result.data.path;

wx.showToast({

title: msg+"\n\r"+path,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}

//自定义异常

var sta = result.data.status;

if(sta != 200){

var msg = result.data.message;

wx.showToast({

title: msg,

icon: ‘loading‘,

duration: 1000

});

resolve(null);

return ;

}

resolve(result);

}

});

});

return promisevariable;

}

//暴露公共访问接口

module.exports = {

sendRequest: sendRequest,//公布公共请求接口

}

使用:

var url = "/home/test";

var params = {msg: ‘哈哈哈‘}

requestHandler.sendRequest(url,params).then(values => {

console.log(values.data)

this.setData({

result : values.data

});

})

es6-promise.auto.js

/*!

* @overview es6-promise - a tiny implementation of Promises/A+.

* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)

* @license   Licensed under MIT license

*            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE

* @version   v4.2.4+314e4831

*/

(function (global, factory) {

typeof exports === ‘object‘ && typeof module !== ‘undefined‘ ? module.exports = factory() :

typeof define === ‘function‘ && define.amd ? define(factory) :

(global.ES6Promise = factory());

}(this, (function () { ‘use strict‘;

function objectOrFunction(x) {

var type = typeof x;

return x !== null && (type === ‘object‘ || type === ‘function‘);

}

function isFunction(x) {

return typeof x === ‘function‘;

}

var _isArray = void 0;

if (Array.isArray) {

_isArray = Array.isArray;

} else {

_isArray = function (x) {

return Object.prototype.toString.call(x) === ‘[object Array]‘;

};

}

var isArray = _isArray;

var len = 0;

var vertxNext = void 0;

var customSchedulerFn = void 0;

var asap = function asap(callback, arg) {

queue[len] = callback;

queue[len + 1] = arg;

len += 2;

if (len === 2) {

// If len is 2, that means that we need to schedule an async flush.

// If additional callbacks are queued before the queue is flushed, they

// will be processed by this flush that we are scheduling.

if (customSchedulerFn) {

customSchedulerFn(flush);

} else {

scheduleFlush();

}

}

};

function setScheduler(scheduleFn) {

customSchedulerFn = scheduleFn;

}

function setAsap(asapFn) {

asap = asapFn;

}

var browserWindow = typeof window !== ‘undefined‘ ? window : undefined;

var browserGlobal = browserWindow || {};

var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;

var isNode = typeof self === ‘undefined‘ && typeof process !== ‘undefined‘ && {}.toString.call(process) === ‘[object process]‘;

// test for web worker but not in IE10

var isWorker = typeof Uint8ClampedArray !== ‘undefined‘ && typeof importScripts !== ‘undefined‘ && typeof MessageChannel !== ‘undefined‘;

// node

function useNextTick() {

// node version 0.10.x displays a deprecation warning when nextTick is used recursively

// see https://github.com/cujojs/when/issues/410 for details

return function () {

return process.nextTick(flush);

};

}

// vertx

function useVertxTimer() {

if (typeof vertxNext !== ‘undefined‘) {

return function () {

vertxNext(flush);

};

}

return useSetTimeout();

}

function useMutationObserver() {

var iterations = 0;

var observer = new BrowserMutationObserver(flush);

var node = document.createTextNode(‘‘);

observer.observe(node, { characterData: true });

return function () {

node.data = iterations = ++iterations % 2;

};

}

// web worker

function useMessageChannel() {

var channel = new MessageChannel();

channel.port1.onmessage = flush;

return function () {

return channel.port2.postMessage(0);

};

}

function useSetTimeout() {

// Store setTimeout reference so es6-promise will be unaffected by

// other code modifying setTimeout (like sinon.useFakeTimers())

var globalSetTimeout = setTimeout;

return function () {

return globalSetTimeout(flush, 1);

};

}

var queue = new Array(1000);

function flush() {

for (var i = 0; i < len; i += 2) {

var callback = queue[i];

var arg = queue[i + 1];

callback(arg);

queue[i] = undefined;

queue[i + 1] = undefined;

}

len = 0;

}

function attemptVertx() {

try {

var vertx = Function(‘return this‘)().require(‘vertx‘);

vertxNext = vertx.runOnLoop || vertx.runOnContext;

return useVertxTimer();

} catch (e) {

return useSetTimeout();

}

}

var scheduleFlush = void 0;

// Decide what async method to use to triggering processing of queued callbacks:

if (isNode) {

scheduleFlush = useNextTick();

} else if (BrowserMutationObserver) {

scheduleFlush = useMutationObserver();

} else if (isWorker) {

scheduleFlush = useMessageChannel();

} else if (browserWindow === undefined && typeof require === ‘function‘) {

scheduleFlush = attemptVertx();

} else {

scheduleFlush = useSetTimeout();

}

function then(onFulfillment, onRejection) {

var parent = this;

var child = new this.constructor(noop);

if (child[PROMISE_ID] === undefined) {

makePromise(child);

}

var _state = parent._state;

if (_state) {

var callback = arguments[_state - 1];

asap(function () {

return invokeCallback(_state, child, callback, parent._result);

});

} else {

subscribe(parent, child, onFulfillment, onRejection);

}

return child;

}

/**

`Promise.resolve` returns a promise that will become resolved with the

passed `value`. It is shorthand for the following:

```javascript

let promise = new Promise(function(resolve, reject){

resolve(1);

});

promise.then(function(value){

// value === 1

});

```

Instead of writing the above, your code now simply becomes the following:

```javascript

let promise = Promise.resolve(1);

promise.then(function(value){

// value === 1

});

```

@method resolve

@static

@param {Any} value value that the returned promise will be resolved with

Useful for tooling.

@return {Promise} a promise that will become fulfilled with the given

`value`

*/

function resolve$1(object) {

/*jshint validthis:true */

var Constructor = this;

if (object && typeof object === ‘object‘ && object.constructor === Constructor) {

return object;

}

var promise = new Constructor(noop);

resolve(promise, object);

return promise;

}

var PROMISE_ID = Math.random().toString(36).substring(2);

function noop() {}

var PENDING = void 0;

var FULFILLED = 1;

var REJECTED = 2;

var TRY_CATCH_ERROR = { error: null };

function selfFulfillment() {

return new TypeError("You cannot resolve a promise with itself");

}

function cannotReturnOwn() {

return new TypeError(‘A promises callback cannot return that same promise.‘);

}

function getThen(promise) {

try {

return promise.then;

} catch (error) {

TRY_CATCH_ERROR.error = error;

return TRY_CATCH_ERROR;

}

}

function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {

try {

then$$1.call(value, fulfillmentHandler, rejectionHandler);

} catch (e) {

return e;

}

}

function handleForeignThenable(promise, thenable, then$$1) {

asap(function (promise) {

var sealed = false;

var error = tryThen(then$$1, thenable, function (value) {

if (sealed) {

return;

}

sealed = true;

if (thenable !== value) {

resolve(promise, value);

} else {

fulfill(promise, value);

}

}, function (reason) {

if (sealed) {

return;

}

sealed = true;

reject(promise, reason);

}, ‘Settle: ‘ + (promise._label || ‘ unknown promise‘));

if (!sealed && error) {

sealed = true;

reject(promise, error);

}

}, promise);

}

function handleOwnThenable(promise, thenable) {

if (thenable._state === FULFILLED) {

fulfill(promise, thenable._result);

} else if (thenable._state === REJECTED) {

reject(promise, thenable._result);

} else {

subscribe(thenable, undefined, function (value) {

return resolve(promise, value);

}, function (reason) {

return reject(promise, reason);

});

}

}

function handleMaybeThenable(promise, maybeThenable, then$$1) {

if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {

handleOwnThenable(promise, maybeThenable);

} else {

if (then$$1 === TRY_CATCH_ERROR) {

reject(promise, TRY_CATCH_ERROR.error);

TRY_CATCH_ERROR.error = null;

} else if (then$$1 === undefined) {

fulfill(promise, maybeThenable);

} else if (isFunction(then$$1)) {

handleForeignThenable(promise, maybeThenable, then$$1);

} else {

fulfill(promise, maybeThenable);

}

}

}

function resolve(promise, value) {

if (promise === value) {

reject(promise, selfFulfillment());

} else if (objectOrFunction(value)) {

handleMaybeThenable(promise, value, getThen(value));

} else {

fulfill(promise, value);

}

}

function publishRejection(promise) {

if (promise._onerror) {

promise._onerror(promise._result);

}

publish(promise);

}

function fulfill(promise, value) {

if (promise._state !== PENDING) {

return;

}

promise._result = value;

promise._state = FULFILLED;

if (promise._subscribers.length !== 0) {

asap(publish, promise);

}

}

function reject(promise, reason) {

if (promise._state !== PENDING) {

return;

}

promise._state = REJECTED;

promise._result = reason;

asap(publishRejection, promise);

}

function subscribe(parent, child, onFulfillment, onRejection) {

var _subscribers = parent._subscribers;

var length = _subscribers.length;

parent._onerror = null;

_subscribers[length] = child;

_subscribers[length + FULFILLED] = onFulfillment;

_subscribers[length + REJECTED] = onRejection;

if (length === 0 && parent._state) {

asap(publish, parent);

}

}

function publish(promise) {

var subscribers = promise._subscribers;

var settled = promise._state;

if (subscribers.length === 0) {

return;

}

var child = void 0,

callback = void 0,

detail = promise._result;

for (var i = 0; i < subscribers.length; i += 3) {

child = subscribers[i];

callback = subscribers[i + settled];

if (child) {

invokeCallback(settled, child, callback, detail);

} else {

callback(detail);

}

}

promise._subscribers.length = 0;

}

function tryCatch(callback, detail) {

try {

return callback(detail);

} catch (e) {

TRY_CATCH_ERROR.error = e;

return TRY_CATCH_ERROR;

}

}

function invokeCallback(settled, promise, callback, detail) {

var hasCallback = isFunction(callback),

value = void 0,

error = void 0,

succeeded = void 0,

failed = void 0;

if (hasCallback) {

value = tryCatch(callback, detail);

if (value === TRY_CATCH_ERROR) {

failed = true;

error = value.error;

value.error = null;

} else {

succeeded = true;

}

if (promise === value) {

reject(promise, cannotReturnOwn());

return;

}

} else {

value = detail;

succeeded = true;

}

if (promise._state !== PENDING) {

// noop

} else if (hasCallback && succeeded) {

resolve(promise, value);

} else if (failed) {

reject(promise, error);

} else if (settled === FULFILLED) {

fulfill(promise, value);

} else if (settled === REJECTED) {

reject(promise, value);

}

}

function initializePromise(promise, resolver) {

try {

resolver(function resolvePromise(value) {

resolve(promise, value);

}, function rejectPromise(reason) {

reject(promise, reason);

});

} catch (e) {

reject(promise, e);

}

}

var id = 0;

function nextId() {

return id++;

}

function makePromise(promise) {

promise[PROMISE_ID] = id++;

promise._state = undefined;

promise._result = undefined;

promise._subscribers = [];

}

function validationError() {

return new Error(‘Array Methods must be provided an Array‘);

}

var Enumerator = function () {

function Enumerator(Constructor, input) {

this._instanceConstructor = Constructor;

this.promise = new Constructor(noop);

if (!this.promise[PROMISE_ID]) {

makePromise(this.promise);

}

if (isArray(input)) {

this.length = input.length;

this._remaining = input.length;

this._result = new Array(this.length);

if (this.length === 0) {

fulfill(this.promise, this._result);

} else {

this.length = this.length || 0;

this._enumerate(input);

if (this._remaining === 0) {

fulfill(this.promise, this._result);

}

}

} else {

reject(this.promise, validationError());

}

}

Enumerator.prototype._enumerate = function _enumerate(input) {

for (var i = 0; this._state === PENDING && i < input.length; i++) {

this._eachEntry(input[i], i);

}

};

Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {

var c = this._instanceConstructor;

var resolve$$1 = c.resolve;

if (resolve$$1 === resolve$1) {

var _then = getThen(entry);

if (_then === then && entry._state !== PENDING) {

this._settledAt(entry._state, i, entry._result);

} else if (typeof _then !== ‘function‘) {

this._remaining--;

this._result[i] = entry;

} else if (c === Promise$2) {

var promise = new c(noop);

handleMaybeThenable(promise, entry, _then);

this._willSettleAt(promise, i);

} else {

this._willSettleAt(new c(function (resolve$$1) {

return resolve$$1(entry);

}), i);

}

} else {

this._willSettleAt(resolve$$1(entry), i);

}

};

Enumerator.prototype._settledAt = function _settledAt(state, i, value) {

var promise = this.promise;

if (promise._state === PENDING) {

this._remaining--;

if (state === REJECTED) {

reject(promise, value);

} else {

this._result[i] = value;

}

}

if (this._remaining === 0) {

fulfill(promise, this._result);

}

};

Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {

var enumerator = this;

subscribe(promise, undefined, function (value) {

return enumerator._settledAt(FULFILLED, i, value);

}, function (reason) {

return enumerator._settledAt(REJECTED, i, reason);

});

};

return Enumerator;

}();

/**

`Promise.all` accepts an array of promises, and returns a new promise which

is fulfilled with an array of fulfillment values for the passed promises, or

rejected with the reason of the first passed promise to be rejected. It casts all

elements of the passed iterable to promises as it runs this algorithm.

Example:

```javascript

let promise1 = resolve(1);

let promise2 = resolve(2);

let promise3 = resolve(3);

let promises = [ promise1, promise2, promise3 ];

Promise.all(promises).then(function(array){

// The array here would be [ 1, 2, 3 ];

});

```

If any of the `promises` given to `all` are rejected, the first promise

that is rejected will be given as an argument to the returned promises‘s

rejection handler. For example:

Example:

```javascript

let promise1 = resolve(1);

let promise2 = reject(new Error("2"));

let promise3 = reject(new Error("3"));

let promises = [ promise1, promise2, promise3 ];

Promise.all(promises).then(function(array){

// Code here never runs because there are rejected promises!

}, function(error) {

// error.message === "2"

});

```

@method all

@static

@param {Array} entries array of promises

@param {String} label optional string for labeling the promise.

Useful for tooling.

@return {Promise} promise that is fulfilled when all `promises` have been

fulfilled, or rejected if any of them become rejected.

@static

*/

function all(entries) {

return new Enumerator(this, entries).promise;

}

/**

`Promise.race` returns a new promise which is settled in the same way as the

first passed promise to settle.

Example:

```javascript

let promise1 = new Promise(function(resolve, reject){

setTimeout(function(){

resolve(‘promise 1‘);

}, 200);

});

let promise2 = new Promise(function(resolve, reject){

setTimeout(function(){

resolve(‘promise 2‘);

}, 100);

});

Promise.race([promise1, promise2]).then(function(result){

// result === ‘promise 2‘ because it was resolved before promise1

// was resolved.

});

```

`Promise.race` is deterministic in that only the state of the first

settled promise matters. For example, even if other promises given to the

`promises` array argument are resolved, but the first settled promise has

become rejected before the other promises became fulfilled, the returned

promise will become rejected:

```javascript

let promise1 = new Promise(function(resolve, reject){

setTimeout(function(){

resolve(‘promise 1‘);

}, 200);

});

let promise2 = new Promise(function(resolve, reject){

setTimeout(function(){

reject(new Error(‘promise 2‘));

}, 100);

});

Promise.race([promise1, promise2]).then(function(result){

// Code here never runs

}, function(reason){

// reason.message === ‘promise 2‘ because promise 2 became rejected before

// promise 1 became fulfilled

});

```

An example real-world use case is implementing timeouts:

```javascript

Promise.race([ajax(‘foo.json‘), timeout(5000)])

```

@method race

@static

@param {Array} promises array of promises to observe

Useful for tooling.

@return {Promise} a promise which settles in the same way as the first passed

promise to settle.

*/

function race(entries) {

/*jshint validthis:true */

var Constructor = this;

if (!isArray(entries)) {

return new Constructor(function (_, reject) {

return reject(new TypeError(‘You must pass an array to race.‘));

});

} else {

return new Constructor(function (resolve, reject) {

var length = entries.length;

for (var i = 0; i < length; i++) {

Constructor.resolve(entries[i]).then(resolve, reject);

}

});

}

}

/**

`Promise.reject` returns a promise rejected with the passed `reason`.

It is shorthand for the following:

```javascript

let promise = new Promise(function(resolve, reject){

reject(new Error(‘WHOOPS‘));

});

promise.then(function(value){

// Code here doesn‘t run because the promise is rejected!

}, function(reason){

// reason.message === ‘WHOOPS‘

});

```

Instead of writing the above, your code now simply becomes the following:

```javascript

let promise = Promise.reject(new Error(‘WHOOPS‘));

promise.then(function(value){

// Code here doesn‘t run because the promise is rejected!

}, function(reason){

// reason.message === ‘WHOOPS‘

});

```

@method reject

@static

@param {Any} reason value that the returned promise will be rejected with.

Useful for tooling.

@return {Promise} a promise rejected with the given `reason`.

*/

function reject$1(reason) {

/*jshint validthis:true */

var Constructor = this;

var promise = new Constructor(noop);

reject(promise, reason);

return promise;

}

function needsResolver() {

throw new TypeError(‘You must pass a resolver function as the first argument to the promise constructor‘);

}

function needsNew() {

throw new TypeError("Failed to construct ‘Promise‘: Please use the ‘new‘ operator, this object constructor cannot be called as a function.");

}

/**

Promise objects represent the eventual result of an asynchronous operation. The

primary way of interacting with a promise is through its `then` method, which

registers callbacks to receive either a promise‘s eventual value or the reason

why the promise cannot be fulfilled.

Terminology

-----------

- `promise` is an object or function with a `then` method whose behavior conforms to this specification.

- `thenable` is an object or function that defines a `then` method.

- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).

- `exception` is a value that is thrown using the throw statement.

- `reason` is a value that indicates why a promise was rejected.

- `settled` the final resting state of a promise, fulfilled or rejected.

A promise can be in one of three states: pending, fulfilled, or rejected.

Promises that are fulfilled have a fulfillment value and are in the fulfilled

state.  Promises that are rejected have a rejection reason and are in the

rejected state.  A fulfillment value is never a thenable.

Promises can also be said to *resolve* a value.  If this value is also a

promise, then the original promise‘s settled state will match the value‘s

settled state.  So a promise that *resolves* a promise that rejects will

itself reject, and a promise that *resolves* a promise that fulfills will

itself fulfill.

Basic Usage:

------------

```js

let promise = new Promise(function(resolve, reject) {

// on success

resolve(value);

// on failure

reject(reason);

});

promise.then(function(value) {

// on fulfillment

}, function(reason) {

// on rejection

});

```

Advanced Usage:

---------------

Promises shine when abstracting away asynchronous interactions such as

`XMLHttpRequest`s.

```js

function getJSON(url) {

return new Promise(function(resolve, reject){

let xhr = new XMLHttpRequest();

xhr.open(‘GET‘, url);

xhr.onreadystatechange = handler;

xhr.responseType = ‘json‘;

xhr.setRequestHeader(‘Accept‘, ‘application/json‘);

xhr.send();

function handler() {

if (this.readyState === this.DONE) {

if (this.status === 200) {

resolve(this.response);

} else {

reject(new Error(‘getJSON: `‘ + url + ‘` failed with status: [‘ + this.status + ‘]‘));

}

}

};

});

}

getJSON(‘/posts.json‘).then(function(json) {

// on fulfillment

}, function(reason) {

// on rejection

});

```

Unlike callbacks, promises are great composable primitives.

```js

Promise.all([

getJSON(‘/posts‘),

getJSON(‘/comments‘)

]).then(function(values){

values[0] // => postsJSON

values[1] // => commentsJSON

return values;

});

```

@class Promise

@param {Function} resolver

Useful for tooling.

@constructor

*/

var Promise$2 = function () {

function Promise(resolver) {

this[PROMISE_ID] = nextId();

this._result = this._state = undefined;

this._subscribers = [];

if (noop !== resolver) {

typeof resolver !== ‘function‘ && needsResolver();

this instanceof Promise ? initializePromise(this, resolver) : needsNew();

}

}

/**

The primary way of interacting with a promise is through its `then` method,

which registers callbacks to receive either a promise‘s eventual value or the

reason why the promise cannot be fulfilled.

```js

findUser().then(function(user){

// user is available

}, function(reason){

// user is unavailable, and you are given the reason why

});

```

Chaining

--------

The return value of `then` is itself a promise.  This second, ‘downstream‘

promise is resolved with the return value of the first promise‘s fulfillment

or rejection handler, or rejected if the handler throws an exception.

```js

findUser().then(function (user) {

return user.name;

}, function (reason) {

return ‘default name‘;

}).then(function (userName) {

// If `findUser` fulfilled, `userName` will be the user‘s name, otherwise it

// will be `‘default name‘`

});

findUser().then(function (user) {

throw new Error(‘Found user, but still unhappy‘);

}, function (reason) {

throw new Error(‘`findUser` rejected and we‘re unhappy‘);

}).then(function (value) {

// never reached

}, function (reason) {

// if `findUser` fulfilled, `reason` will be ‘Found user, but still unhappy‘.

// If `findUser` rejected, `reason` will be ‘`findUser` rejected and we‘re unhappy‘.

});

```

If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.

```js

findUser().then(function (user) {

throw new PedagogicalException(‘Upstream error‘);

}).then(function (value) {

// never reached

}).then(function (value) {

// never reached

}, function (reason) {

// The `PedgagocialException` is propagated all the way down to here

});

```

Assimilation

------------

Sometimes the value you want to propagate to a downstream promise can only be

retrieved asynchronously. This can be achieved by returning a promise in the

fulfillment or rejection handler. The downstream promise will then be pending

until the returned promise is settled. This is called *assimilation*.

```js

findUser().then(function (user) {

return findCommentsByAuthor(user);

}).then(function (comments) {

// The user‘s comments are now available

});

```

If the assimliated promise rejects, then the downstream promise will also reject.

```js

findUser().then(function (user) {

return findCommentsByAuthor(user);

}).then(function (comments) {

// If `findCommentsByAuthor` fulfills, we‘ll have the value here

}, function (reason) {

// If `findCommentsByAuthor` rejects, we‘ll have the reason here

});

```

Simple Example

--------------

Synchronous Example

```javascript

let result;

try {

result = findResult();

// success

} catch(reason) {

// failure

}

```

Errback Example

```js

findResult(function(result, err){

if (err) {

// failure

} else {

// success

}

});

```

Promise Example;

```javascript

findResult().then(function(result){

// success

}, function(reason){

// failure

});

```

Advanced Example

--------------

Synchronous Example

```javascript

let author, books;

try {

author = findAuthor();

books  = findBooksByAuthor(author);

// success

} catch(reason) {

// failure

}

```

Errback Example

```js

function foundBooks(books) {

}

function failure(reason) {

}

findAuthor(function(author, err){

if (err) {

failure(err);

// failure

} else {

try {

findBoooksByAuthor(author, function(books, err) {

if (err) {

failure(err);

} else {

try {

foundBooks(books);

} catch(reason) {

failure(reason);

}

}

});

} catch(error) {

failure(err);

}

// success

}

});

```

Promise Example;

```javascript

findAuthor().

then(findBooksByAuthor).

then(function(books){

// found books

}).catch(function(reason){

// something went wrong

});

```

@method then

@param {Function} onFulfilled

@param {Function} onRejected

Useful for tooling.

@return {Promise}

*/

/**

`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same

as the catch block of a try/catch statement.

```js

function findAuthor(){

throw new Error(‘couldn‘t find that author‘);

}

// synchronous

try {

findAuthor();

} catch(reason) {

// something went wrong

}

// async with promises

findAuthor().catch(function(reason){

// something went wrong

});

```

@method catch

@param {Function} onRejection

Useful for tooling.

@return {Promise}

*/

Promise.prototype.catch = function _catch(onRejection) {

return this.then(null, onRejection);

};

/**

`finally` will be invoked regardless of the promise‘s fate just as native

try/catch/finally behaves

Synchronous example:

```js

findAuthor() {

if (Math.random() > 0.5) {

throw new Error();

}

return new Author();

}

try {

return findAuthor(); // succeed or fail

} catch(error) {

return findOtherAuther();

} finally {

// always runs

// doesn‘t affect the return value

}

```

Asynchronous example:

```js

findAuthor().catch(function(reason){

return findOtherAuther();

}).finally(function(){

// author was either found, or not

});

```

@method finally

@param {Function} callback

@return {Promise}

*/

Promise.prototype.finally = function _finally(callback) {

var promise = this;

var constructor = promise.constructor;

return promise.then(function (value) {

return constructor.resolve(callback()).then(function () {

return value;

});

}, function (reason) {

return constructor.resolve(callback()).then(function () {

throw reason;

});

});

};

return Promise;

}();

Promise$2.prototype.then = then;

Promise$2.all = all;

Promise$2.race = race;

Promise$2.resolve = resolve$1;

Promise$2.reject = reject$1;

Promise$2._setScheduler = setScheduler;

Promise$2._setAsap = setAsap;

Promise$2._asap = asap;

/*global self*/

function polyfill() {

var local = void 0;

if (typeof global !== ‘undefined‘) {

local = global;

} else if (typeof self !== ‘undefined‘) {

local = self;

} else {

try {

local = Function(‘return this‘)();

} catch (e) {

throw new Error(‘polyfill failed because global object is unavailable in this environment‘);

}

}

var P = local.Promise;

if (P) {

var promiseToString = null;

try {

promiseToString = Object.prototype.toString.call(P.resolve());

} catch (e) {

// silently ignored

}

if (promiseToString === ‘[object Promise]‘ && !P.cast) {

return;

}

}

local.Promise = Promise$2;

}

// Strange compat..

Promise$2.polyfill = polyfill;

Promise$2.Promise = Promise$2;

Promise$2.polyfill();

return Promise$2;

})));

//# sourceMappingURL=es6-promise.auto.map

原文地址:https://www.cnblogs.com/gentrywolf/p/10115336.html

时间: 2024-07-30 22:50:53

微信小程序,封装同步请求的相关文章

微信小程序封装http请求

Q:网上很多封装http请求的方法,我就收藏了一种比较通俗易懂的方法. A:对封装的要求:一是在封装函数里设置header,发送token.二是在封装函数里对后台返回的参数作出统一处理,例如如果statusCode不返回200,统一做出异常处理,相当于过滤功能. var API_COMMON = 'http://192.168.2.105:8080/' var requestHandler = { params: {}, success: function (res) { // success

监控微信小程序wx.request请求失败

在微信小程序里,与后台服务器交互的主要接口函数是wx.request(),用于发起 HTTPS 网络请求.其重要性不言而喻.然而,却经常遇到请求失败的问题,笔者特意谷歌"wx.request 请求失败",可以搜索到很多相关的文章,下面列出一些: wx.request 失败| 微信开放社区 微信小程序 wx.request 请求失败- SegmentFault 思否 小程序部分机型小程序用户无法发起 wx.request 请求,网络错误问题 ... wx.request()失败,requ

微信小程序开发:http请求

在微信小程序进行网络通信,只能和指定的域名进行通信,微信小程序包括四种类型的网络请求. 普通HTTPS请求(wx.request) 上传文件(wx.uploadFile) 下载文件(wx.downloadFile) WebSocket通信(wx.connectSocket) 这里以介绍wx.request,wx.uploadFile,wx.dowloadFile三种网络请求为主 设置域名 要微信小程序进行网络通信,必须先设置域名,不然会出现错误: URL 域名不合法,请在 mp 后台配置后重试

微信小程序封装请求的js

1.配置访问服务器的地址config.js: const config = {//192.18.1.2:8083 https://www.so.com/ api_base_url: 'http://192.168.1.12:8083', // api_base_url:"https://www.baidu.com", img_base_url: '' } export { config } 2.封装http请求http.js: import { config } from './con

微信小程序HTTP接口请求封装

1.方法封装(新建文件夹util,工具文件,在文件夹下创建request.js文件,用于对方法封装)request.js: var app = getApp(); //项目URL相同部分,减轻代码量,同时方便项目迁移 //这里因为我是本地调试,所以host不规范,实际上应该是你备案的域名信息 var host = 'http://localhost:8081/demo/'; /** * POST请求, * URL:接口 * postData:参数,json类型 * doSuccess:成功的回调

微信小程序:POST请求data数据请求不到

最近开始开发小程序,遇到许多小问题,直奔主题. wx.request()是微信封装的ajax请求方法,也是小程序中ajax唯一的一个方法,被放在了API文档的第一个位置,的确使用率是最高的. 但是wx.request()并非像jquery中的$.ajax()一样,它还需要开发者在具体情况中做一些调整. 在直接发送POST请求时,请求成功,可以触发success回调,但是请求到的数据为空.这其中的问题出在https请求的header上.(上图为header未设置时的情况) 当把请求header的c

微信小程序封装bindinput &amp; 输入框出现清空图标 &amp; wx:key对input的影响

Q:我以前写小程序每次获取输入内容,都要写一个方法,觉得十分麻烦,所以写了一个通用的方法. A:我能想到的原理就是,不同的input所带的data不同,bindinput事件setData不同的data. <input class="weui-input" data-inputName='name' placeholder="你的姓名" bindinput="bindKeyInput" value='{{item}}' bindfocus=

微信小程序封装自定义弹窗

最近在做小程序的登录,需要同时获取用户手机号和头像昵称等信息,但是小程序又不支持单个接口同时获取两种数据,因此想到自定义一个弹窗,通过弹窗按钮触发获取手机号事件.记录一下. 具体代码如下: 业务代码中: 在业务代码中引入dialog组件即可 <dialog visible="{{dialogVisible}}" showFooter="{{footerVisible}}" title="测试一下"> <view class='d

博客与微信小程序的同步

在此之前,先说说自己最近的打算,才购买了阿里云的服务器,想做一个网站和图床网盘之类的方便自己使用. 考虑到小程序,又打算将自己的博客内容放到小程序中.从零开发实属困难,应该还要一段时间才能完成. 目前微信公众号已经在逐步的完善中. 这里不要脸的推荐一波. 原文地址:https://www.cnblogs.com/loufangcheng/p/11917318.html

微信小程序设置全局请求URL 封装wx.request请求

app.js: App({ //设置全局请求URL globalData:{ URL: 'https://www.oyhdo.com', }, /** * 封装wx.request请求 * method: 请求方式 * url: 请求地址 * data: 要传递的参数 * callback: 请求成功回调函数 * errFun: 请求失败回调函数 **/ wxRequest(method, url, data, callback, errFun) { wx.request({ url: url,