Перейти к содержимому

Angularjs как return string из then

  • автор:

Promise.prototype.then()

Метод then() возвращает Promise . Метод может принимать два аргумента: колбэк-функции для случаев выполнения и отклонения промиса.

Примечание: Если один или оба аргумента отсутствуют или их значения не функции, то then пропустит их и не выбросит ошибку. Если для Promise , который переходит в состояние выполнен или отклонён вызван метод then , и у данного метода нет нужного обработчика, то в таком случае then просто возвращает промис с состоянием начального Promise , для которого then был вызван.

Синтаксис

p.then(onFulfilled[, onRejected]); p.then(value => < // выполнение >, reason => < // отклонение >);

Параметры

onFulfilled Необязательный

Function вызывается, когда Promise выполнен. Эта функция принимает один аргумент, значение с которым промис был выполнен. Если значение onFulfilled не функция, то оно автоматически заменяется на «Identity» функцию (возвращает полученный аргумент)

Function вызывается, когда Promise отклонён. Эта функция принимает один аргумент, значение с которым промис был отклонён. Если значение onRejected не функция, то оно автоматически заменяется на «Thrower» функцию (выбрасывает полученный аргумент как ошибку)

Описание

Так как и метод then , и метод Promise.prototype.catch() возвращают Promise , их можно вызвать цепочкой — эта операция называется соединение.

Примеры

Использование метода then

var p1 = new Promise(function (resolve, reject)  resolve("Успех!"); // или // reject("Ошибка!"); >); p1.then( function (value)  console.log(value); // Успех! >, function (reason)  console.log(reason); // Ошибка! >, ); 

Соединение

Так как метод then возвращает промис ( Promise ), вы можете объединить несколько вызовов then в цепочку. Значения возвращаемые из колбэков onFulfilled или onRejected будут автоматически обёрнуты в промис.

var p2 = new Promise(function (resolve, reject)  resolve(1); >); p2.then(function (value)  console.log(value); // 1 return value + 1; >).then(function (value)  console.log(value); // 2 >); p2.then(function (value)  console.log(value); // 1 >); 

Вы также можете соединить одну функцию, имеющую подобный с промисами API, с другой функцией.

function fetch_current_data()  // API функции fetch() возвращает промис. Эта функция // имеет аналогичный API, за исключением значения в случае выполнения return fetch("current-data.json").then((response) =>  if (response.headers.get("content-type") != "application/json")  throw new TypeError(); > var j = response.json(); // можем что-нибудь делать с j return j; // в случае выполнения промиса, значение // передаётся в fetch_current_data().then() >); > 

Если onFulfilled возвращает промис, возвращаемое значение может быть выполнено (resolved) / отклонено (rejected) промисом.

function resolveLater(resolve, reject)  setTimeout(function ()  resolve(10); >, 1000); > function rejectLater(resolve, reject)  setTimeout(function ()  reject(20); >, 1000); > var p1 = Promise.resolve("foo"); var p2 = p1.then(function ()  // Возвращает промис, который будет разрешен значением 10 через 1 секунду return new Promise(resolveLater); >); p2.then( function (v)  console.log("resolved", v); // "resolved", 10 >, function (e)  // не вызвано console.log("rejected", e); >, ); var p3 = p1.then(function ()  // Возвращает промис, который будет отброшен значением 20 через 1 секунду return new Promise(rejectLater); >); p3.then( function (v)  // не console.log("resolved", v); >, function (e)  console.log("rejected", e); // "rejected", 20 >, ); 

Спецификация

Specification
ECMAScript Language Specification
# sec-promise.prototype.then

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

  • Promise
  • Promise.prototype.catch()

Angular Promise .then() return value [duplicate]

@Jota.Toledo I want to get Latitude and Longitude value from my API. After getting operation, i want to use that variable in another function to create map icon.

Jun 7, 2019 at 22:06

1 Answer 1

Better practise is to use Observable :

import < catchError >from 'rxjs/operators'; import < throwError >from 'rxjs'; bbb() < return this.http.get(this.url) .pipe( catchError(err =>< console.log('err', err); return throwError('Something bad happened; please try again later.'); >); > 

And, then simply just subscribe to bbb :

import < Subscription >from 'rxjs'; testSubscription: Subscription; ngAfterContentInit() < this.testSubscription = this.bbb() .subscribe(son =>< console.log('son', son); // here you get the result >); > 

Don’t forget to unsubscribe :

ngOnDestroy()

If you still want to use Promise :

To get the result of bbb :

ngAfterContentInit() < this.bbb() .then(son =>< console.log('son', son); // here you get the result >) .catch(err => < console.log(err); >); > 

answered Jun 7, 2019 at 22:00
3,299 2 2 gold badges 13 13 silver badges 30 30 bronze badges
Can i reach son variable in any function? Because i have to create map icon on googlemaps.
Jun 7, 2019 at 22:04

You’ll get son asyncroniously (after some time). so if you want to use it in some function, call that function after you’ll get the result (inside of subscription callback or than )

Jun 7, 2019 at 22:08

Good that you’re mentioning the observable way, but (1) catchError has to return an Observable and (2) the $ suffix is usually only used for Observables but not Subscriptions.

Return string from promise result

I want to have an wrapper function arround this $translate service: https://angular-translate.github.io/docs/#/guide/03_using-translate-service so we can use those function easily in our code by calling $language.translate(‘keyword’) instead of the promise. So, I create a new service in my app which should do that work. It’s a very simple function but it’s returning undefined or [Object Object] .

 angularApp.factory("$language", ['$translate', function($translate)< function trans(keyword)< console.log("translate in $language", keyword); return $translate(keyword).then(function(msg) < console.log("translation successfull", msg); return msg; >, function(translationId)< console.log("translation is not known", translationId); return translationId >) > return < translate : trans >>]); 

In both cases, when translation is known or not, the console.log() shows me the right string, but on my page it’s showing [object object] or undefined (when I remove the first return right before $translate(keyword) . When I use the filter like <<:: "KEYWORD" | translate>> it works fine. How can I let my function return the string with the translation or the translationId (which is actually the same as the keyword when there is no translation found)?

  • angularjs
  • angular-promise
  • angular-translate

Javascript – AngularJS http return value

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.

My first attempt was:

this.readParameter = function(key) < $http(< method: "GET", url: "XXXXXXX", headers: < 'Content-Type': 'application/json' >>).then(function successCallback(response) < return response.data; >, function errorCallback(response) < throw new Error("Error"); >) >; 

But of course it does not work because of Angular async features (response.data is undefined)

What is the way to do it? I just want to return the value (string), so I can use this function like

var a = readParameter("key1") 
Best Solution

What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.

Delegator pattern works great here to assign $http task to some service and use callback method for response.

Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)

Basic example of Callback

var myVariable = ''; function myFunction (key, callback) < $http(< method: "GET", url: "XXXXXXX", headers: < 'Content-Type': 'application/json' >>).then(function successCallback(response) < callback(response); >, function errorCallback(response) < throw new Error("Error"); >) >; function myCallbackFunction(response) < myVariable = response.data; // assign value to variable // Do some work after getting response >myFunction('MY_KEY', myCallbackFunction); 

This is basic example to set value but instead use callback pattern from above example.

var myvariable = ''; function myFunction (key) < $http(< method: "GET", url: "XXXXXXX", headers: < 'Content-Type': 'application/json' >>).then(function successCallback(response) < myvariable = response.data; // set data to myvariable // Do something else on success response >, function errorCallback(response) < throw new Error("Error"); >) >; myFunction('MY_KEY'); 
Related Solutions
Javascript – Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”

I use javascript:void(0) .

Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() < //Some code return false; >

But then they forget to use return doSomething() in the onclick and just use doSomething() .

A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.

A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:

onclick="someFunc.call(this)" 
onclick="someFunc.apply(this, arguments)" 

Using javascript:void(0) avoids all of the above headaches, and I haven’t found any examples of a downside.

So if you’re a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:

Use href=»#» , make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false .

The second is clearly much easier to communicate.

Javascript – How to check if an array includes a value in JavaScript

Modern browsers have Array#includes , which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

You can also use Array#indexOf , which is less direct, but doesn’t require polyfills for outdated browsers.

console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true

Many frameworks also offer similar methods:

  • jQuery: $.inArray(value, array, [fromIndex])
  • Underscore.js: _.contains(array, value) (also aliased as _.include and _.includes )
  • Dojo Toolkit: dojo.indexOf(array, value, [fromIndex, findLast])
  • Prototype: array.indexOf(value)
  • MooTools: array.indexOf(value)
  • MochiKit: findValue(array, value)
  • MS Ajax: array.indexOf(value)
  • Ext: Ext.Array.contains(array, value)
  • Lodash: _.includes(array, value, [from]) (is _.contains prior 4.0.0)
  • Ramda: R.includes(value, array)

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

Related Question
  • Javascript – Set a default parameter value for a JavaScript function
  • Javascript – Sort array of objects by string property value
  • Javascript – event.preventDefault() vs. return false
  • Javascript – Why does ++[[]][+[]]+[+[]] return the string “10”
  • Javascript – How does data binding work in AngularJS
  • Javascript – How to return the response from an asynchronous call
  • AngularJS: Service vs provider vs factory

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *